package com.shop.wk.config.custom;

import com.alibaba.fastjson.JSONObject;
import com.shop.wk.common.constant.HttpCode;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;

/**
 * @author 日月星辰
 * @date 2020/12/25 22:52
 * @description
 */
@Component
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

	@Override
	public ResponseEntity translate(Exception e) throws Exception {
		JSONObject body = new JSONObject();
		body.put("code", HttpCode.FAIL);

		MultiValueMap headers = new HttpHeaders();
		headers.set("Cache-Control", "no-store");
		headers.set("Pragma", "no-cache");
		headers.set("Content-Type", "application/json;charset=UTF-8");

		if (e instanceof InvalidGrantException) {
			body.put("message", "账号或密码错误 - " + e.getMessage());
		}
		else if (e instanceof InvalidTokenException) {
			body.put("message", "token无效 - " + e.getMessage());
		}

		else {
			body.put("message", e.getMessage());
		}

		ResponseEntity entity = new ResponseEntity(body, headers, HttpStatus.OK);
		return entity;
	}

}
